package com.atguigu.day04;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.ConnectedStreams;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.CoMapFunction;

/**
 * @author Felix
 * @date 2024/4/2
 * 该案例演示了合流算子-connect
 * 需求：从8888端口读取字符串，从8889端口读取数字，将2条流合并在一起并打印输出
 */
public class Flink06_Connect {
    public static void main(String[] args) throws Exception {
        //TODO 1.指定流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());
        //TODO 2.从8888端口读取字符串
        DataStreamSource<String> ds1 = env.socketTextStream("hadoop102", 8888);
        //TODO 3.从8889端口读取数字
        SingleOutputStreamOperator<Integer> ds2 = env
                .socketTextStream("hadoop102", 8889)
                .map(Integer::parseInt);
        //TODO 4.合并两条流
        ConnectedStreams<String, Integer> connectDS = ds1.connect(ds2);
        //TODO 5.对合流后的数据进行处理   加前缀标记
        SingleOutputStreamOperator<String> mapDS = connectDS.map(
                new CoMapFunction<String, Integer, String>() {
                    //处理第一条流中的数据
                    @Override
                    public String map1(String value) throws Exception {
                        return "字符串：" + value;
                    }

                    //处理第二条流中数据
                    @Override
                    public String map2(Integer value) throws Exception {
                        return "数字:" + value;
                    }
                }
        );
        //TODO 6. 打印
        mapDS.print();

        //TODO 7.提交作业
        env.execute();

    }
}
